layui.use([ 'form', 'table' , 'upload', 'element'], function() {
	var form = layui.form;
	var table = layui.table;
	var upload = layui.upload;
	var element = layui.element;
	var roleData;
	var layerIndex;
	var processInstanceFileIdStr;
	var taskIdStr = ""; //任务ID
	var processInstanceIdStr;
	var type;//流程类型
	var roleId = "";
	var sysuser;
	var isUpload = false;//是否可以更改上传程序数据文件
	var $ = layui.$, active = {
		reload : function() {
			var nameText = $('#nameText');
			var numberText = $('#numberText');
			// 执行重载
			table.reload('userReload', {
				page : {
					curr : 1
				// 重新从第 1 页开始
				},
				where : {
					nameText : nameText.val(),
					numberText : numberText.val(),
				}
			});
			element.render('breadcrumb');
		}
	};
	
	//长轮询
	var getting = {
	        url:'../../activiti/taskList',        
	        data:{isProcessInstanceRead:0},
	        success:function(result) {
        	    var data = JSON.parse(result);
	    		if(data.data.length < 1){
	    			$("#isProcessInstanceReadSpan").css("display",'none');
	    		}else{
	    			$("#isProcessInstanceReadSpan").html(data.data.length);
	    			$("#isProcessInstanceReadSpan").css("display",'inline-block');
	    		}
	    		//关键在这里，回调函数内再次请求Ajax
	    		setTimeout( function(){$.ajax(getting);}, 60 * 1000 );	    		  
	        },
	        error:function(res){
	            $.ajax($getting);
	         }	        
	}  
	
	//启动轮询
	$.ajax(getting);
	
	$.ajax({
		type: 'post',
	    url: '../../sysuser/findUserRole',
	    async: false,
	    success: function(result){
	    	sysuser = result;
	    	roleId = result.role_id;	
	    }		
	});

	/* 异步部门Select */
	var url = "../../sysrole/departmentSelection";
	$.get(url, function(result) {
		var data = JSON.parse(result);
		var departments = data.department;
		var roleSelect = $("#departmentSelect");
		$.each(departments, function(index, data) {
			var deptOption = $("<option value='" + data.dept_id + "'>" + data.dept_name + "</option>");
			roleSelect.append(deptOption);
		});
		form.render('select');
	});

	/* 异步项目类型Select */
	var url = "../../sysrole/projectTypeSelectionByDepartmentId";
	$.get(url, {departmentId: sysuser.department},function(result) {
		var project_types = result;
		var roleSelect = $("#projectTypeSelect");
		$.each(project_types, function(index, data) {
			var deptOption = $("<option value='" + data.id + "' data-parentType='"+ data.parent_type +"'>" + data.type + "</option>");
			roleSelect.append(deptOption);
		});
		form.render('select');
	});
	
	
	form.on('select(projectTypeFilter)', function (data) {
		$("#formProjectSelectId").empty();
		var parentType = $('#projectTypeSelect option:selected').attr("data-parentType");
        $.ajax({
            url: "../../project/getProjectSelection",
            dataType: 'json',
            data: {
            	condtions: parentType
            },
            success: function (result) {
            	var project = result.data;
        		var projectSelect = $("#formProjectSelectId");
        		$.each(project, function(index, reulst) {
        			var deptOption = $("<option value='" + reulst.id + "'>" + (parentType == "0" ? reulst.name : reulst.projectName) + "</option>");
        			projectSelect.append(deptOption);
        		});
        		form.render('select');
            }
        });
        
    });

//	form.on('select(departmentFilter)', function(data){
//        $.getJSON("../../sysrole/departmentStaffSelection?departmen_id="+data.value, function(data){
//            var optionstring = ""; 
//            $.each(data.sysuser, function(i,item){
//                optionstring += "<option value=\"" + item.id + "\" >" + item.name + "</option>";
//            });
//            $("#departmentStaffSelect").html('<option value=""></option>' + optionstring);          
//        });
//	});

	table.render({
		elem : '#sysuserTable',
		url : '../../activiti/taskList',
		toolbar : '#toolbarSysuser',
		title : '任务表',
		cols : [ [ {
			type : 'checkbox',
			fixed : 'left'
		}, {
			field : 'processInstanceId',
			title : '流程编号',
			width : 100,
			fixed : 'left',
			unresize : true,
			sort : true
		}, {
			field : 'project_name',
			title : '流程名称'
		}, {
			field : 'projectPlatName',
			title : '所属项目或平台',
			sort : true
		},{
			field : 'CREATE_TIME_',
			title : '创建时间',
			sort : true
		},{
			field : 'NAME_',
			title : '当前节点',
		},{
			field : 'isProcessInstanceRead',
			title : '状态',
			width : 100,
			templet: function(d){return d.isProcessInstanceRead == 0 ? '未读' : '已读'}			
		}, {
			field : 'type_id',
			title : '流程类型'
		}, {
			field : 'ID_',
			hide : true
		}, {
			fixed : 'right',
			title : '操作',			
			width : roleId == "1" ? 200 : 150,
			templet: function(d){
				if(roleId == "1"){
					return "<a class='layui-btn layui-btn-normal layui-btn-xs' lay-event='approval'>"+ (d.NAME_ =="审批" ? "审批" : "移交")  +"</a>" + 
					"<a class='layui-btn layui-btn-xs' lay-event='edit'>详情</a>"+
					"<a class='layui-btn layui-btn-warm layui-btn-xs' lay-event='operationRecord'>记录</a>"+
			         "<a class='layui-btn layui-btn-danger layui-btn-xs' lay-event='del'>删除</a>"
				}else{
					return "<a class='layui-btn layui-btn-normal layui-btn-xs' lay-event='approval'>"+ (d.NAME_ =="审批" ? "审批" : "移交" ) +"</a>" + 
					"<a class='layui-btn layui-btn-xs' lay-event='edit'>详情</a>"+
					"<a class='layui-btn layui-btn-warm layui-btn-xs' lay-event='operationRecord'>记录</a>"
				}
			}
		} ] ],
		id : 'userReload',
		page : true,
		height : $(window).height() - 50,
		done : function() {
			$.getJSON("../../sysrole/projectTypeSelection", function(data) {
				var project_types = data.project_type;
				$("[data-field='type_id']").children().each(function() {
					for (var i = 0; i < project_types.length; i++) {
						if ($(this).text() == project_types[i].id) {
							$(this).text(project_types[i].type);
							break;
						}
					}
				});
			});
		}
	});

	// 头工具栏事件
	table.on('toolbar(sysuserTable)', function(obj) {
		switch (obj.event) {
		case 'addEmplpyeeBtn':
			/* 再弹出添加界面 */
			layer.open({
				type : 1,
				title : "添加新流程",
				skin : "layui-layer-lan",
				area : [ "50%" ],
				btn : [ '保存', '取消' ],
				content : $("#userAdd"),
				success : function(layero) {
					var btn = layero.find('.layui-layer-btn');
					btn.css('text-align', 'center');
					/* 渲染表单 */
					form.render();
					document.getElementById("addEmployeeForm").reset();// 清空form表单的值
					$("#formProjectSelectId").empty()
				},
				yes : function(index, layero) {
					// 限制输入框中不能用空值
					var num = 0;
					var exsit = false;
					$("#addEmployeeForm input[type$='text']").each(function(n) {
						if ($(this).val() == "") {
							num++
						}
					});
					if (num > 0) {
						layer.msg('输入框不能为空');
						return false;
					}
					var project_name = $('#project_name').val();
					var type_id = $('#projectTypeSelect option:selected').val();
					var projectId = $('#formProjectSelectId option:selected').val();
					$.ajax({
						type : "POST",// 方法类型
						dataType : "json",// 预期服务器返回的数据类型
						url : "../../activiti/isProjectDetailsNameExist",// url
						data : {project_name : project_name},
						async:false,
						success : function(result) {
						    if(result.data=="1"){
						    	layer.msg("流程名称已存在");
						    	exsit = true;
						    }else if(result.data=="2"){
						    	layer.msg("判断流程名称是否已存在时出错");
						    	exsit = true;
						    }
						}						
					});
					if(exsit){
						return false;
					}
					if(type_id==1){
						project_name = project_name + "_program";
					}else if(type_id==2){
						project_name = project_name + "_calibration";
					}else if(type_id==3){
						project_name = project_name + "_sample";
					}else if(type_id==4){
						project_name = project_name + "_OTS";
					}
					$.ajax({
						type : "POST",// 方法类型
						dataType : "json",// 预期服务器返回的数据类型
						url : "../../activiti/newProject",// url
						data : {
							project_name : project_name,
							type_id : type_id,
							projectId : projectId,
						},
						success : function(result) {
							if (result.code == 0) {
								layer.close(index);
								layer.msg('新增项目成功');
								window.location.reload();
							}
						},
						error : function() {
							layer.msg('新增项目失败');
							layer.close(index);
						}
					});
				},
				btn2: function(index, layero){
					layer.close(index);
				}
			});
			break;
		}
		form.render();
	});

	// 监听行工具事件
	table.on('tool(sysuserTable)', function(obj) {
		var data = obj.data;
		taskIdStr = data.ID_;
		processInstanceIdStr = data.processInstanceId;
		type =  data.type_id;
		if (obj.event === 'del') {
			layer.confirm('真的删除项目吗？', function(index) {
				obj.del();
				projectDelete(data.processInstanceId);
				layer.close(index);
			});
		} else if (obj.event === 'edit') {
			$("#processInstanceHistroyRecordUl").empty();
			$("#formCalibrationDataRemarksText").val("");
			 $('#uploadFileNameUl').empty();//清空文件ul
			  $("#demoList").empty();
			  $.ajax({
					type:'post',
					dataType: 'json',
					url: '../../activiti/isUploadFile',
					data: {taskId:data.ID_},
					async:false,
					success: function(result){
						if(result.data){
							  if(data.type_id== 1 || data.type_id == 2){//只有程序下发和标定数据下发才显示上传数据和程序按钮
								  $('#uploadGlobalFileBtn').css("display",'inline-block'); 
							  }else{
								  $('#uploadGlobalFileBtn').css("display",'none'); 
							  }							  							  
							  if(data.type_id== 3 || data.type_id == 4){//只有当时OTS供养和样件需求时才显示合并文件的按钮								  
								  $('#mergeFileBtn').css("display",'inline-block');	 
							  }else{
								  $('#mergeFileBtn').css("display",'none');
							  }							  
							  isUpload = true;
						  }else{
							  $('#uploadGlobalFileBtn').css("display",'none');
							  $('#mergeFileBtn').css("display",'none');
						  }									
					}
				});
			  table.reload('globalFileTableReload',{
					where: { //设定异步数据接口的额外参数，任意设
						processInstanceId: data.processInstanceId
					  }
			   });			  
			showHistoryRecord(data.processInstanceId);
			/* 再弹出编辑界面 */
			layer.open({
				type:1,
				title : "上传",
				skin : "editFile",
				//offset : '50px',
				shadeClose : true,
				area : ['60%','90%'],
				//btn : [ '发起项目', '取消' ],
				content : $("#calibrationDataAdd"),
				success: function(layero,index){
					layerIndex = index;
				}		
			});
			if(data.isProcessInstanceRead == 0){
				$.post("../../activiti/changeIsProcessInstanceRead",{taskId:data.ID_},function(data){
					if(data == "success"){
						var number = $("#isProcessInstanceReadSpan").text();
						if(number-1 < 1){
							$("#isProcessInstanceReadSpan").css("display",'none');
						}else{
							$("#isProcessInstanceReadSpan").html(number-1);
						}					
					}					
				});
			}			
		} else if (obj.event === 'approval') {
			var conditions;
			var transfer;
			$('#departmentStaffSelect').empty();
			$('#departmentSelect').empty();
			$('#approvingOpinionText').val("");
			var isEnd = false;
			$('#currentNode').val(data.NAME_);
			$.ajax({
				type:'post',
				dataType: 'json',
				url: '../../activiti/getNextTaskName',
				data: {taskId:data.ID_},
				 async : false,
				success: function(result){
					conditions = result.data.conditions;
					transfer = result.data.transfer;
					if(transfer.length > 0){
						var transferSelect = $("#transferSelect");
						transferSelect.empty();
						$.each(transfer, function(index, data){
							var deptOption = $("<option value='" + data.condition + "'>" + data.taskName + "</option>");
							transferSelect.append(deptOption);
						});
					}
					if(conditions.length > 0){
						var approvalSelect = $("#approvalSelect");
						approvalSelect.empty();
						$.each(conditions, function(index, data){
							var deptOption = $("<option value='" + data.condition + "'>" + data.taskName + "</option>");
							approvalSelect.append(deptOption);
						});
					}
					if(result.data.transfer[0].taskName == "流程结束"){
						isEnd = true;
						$('#departmentStaffSelect').find("option").remove();;
						$('#departmentSelect').find("option").remove();;
						$('#departmentStaffSelectDiv').css('display','none'); 	
						$('#departmentSelectDiv').css('display','none'); 
					}else{
						$('#departmentStaffSelectDiv').css('display','block'); 	
						$('#departmentSelectDiv').css('display','block'); 
					}										
				}
			});
			$.ajax({
				type : "POST",//方法类型
				url : "../../activiti/findRejectStatusByTaskId",//url
				data : {taskId : data.ID_},
				success : function(result) {	
					if(!isEnd){
						if(result.isDepartment){
							$('#departmentSelect').find("option").remove();;
							$.ajax({
								type: "post", 
								url : "../../sysrole/departmentSelection",
							    async:false,
							    dataType:'json',
							    success: function(data){
									var departments = data.department;
									var roleSelect = $("#departmentSelect");
									$.each(departments, function(index, data) {
										if(data.dept_id == 0){
											return true;
										}
										var deptOption = $("<option value='" + data.dept_id + "'>" + data.dept_name + "</option>");
										roleSelect.append(deptOption);
									});
							    }
							});
							 $('#departmentStaffSelect').empty();
				    		 $('#departmentStaffSelectDiv').css('display','none');				    		 
				    		 $('#departmentSelectDiv').css('display','block'); 		
				    	 }else{	
				    		 $.ajax({
				    			 type: "post", 
				    			 url:"../../sysrole/departmentStaffSelection?departmen_id="+data.department+"&isNextApprovel="+ ($('#transferSelect option:selected').text().indexOf("审批") != -1 ? "0" : "1"),
				    			 async : false,
				    		     success:function(data){			    		    	
				    		    	 var optionstring = ""; 
					    	            $.each(data.sysuser, function(i,item){
					    	                optionstring += "<option value=\"" + item.id + "\" >" + item.name + "</option>";
					    	            });
					    	            $("#departmentStaffSelect").html('<option value=""></option>' + optionstring);  
				    		     }
				    		 });
				    		 $('#departmentStaffSelectDiv').css('display','block');	
				    		 $('#departmentSelect').empty();
				    		 $('#departmentSelectDiv').css('display','none');	
				    	 }
					}	
					if (data.NAME_.indexOf("审批") != -1) {//如果节点有审批二字就显示驳回按钮
						$('#approvingOpinionDiv').css('display','block');
						/* 再弹出编辑界面 */
						layer.open({
							type : 1,
							title : "审批",
							skin : "layui-layer-lan",
							area : [ "45%" ],
							btn :  isEnd == true ? [ '完成','驳回' ]:[ '通过','驳回' ],
							content : $("#approvalPopup"),
							success : function(layero) {
								var btn = layero.find('.layui-layer-btn');
								btn.css('text-align', 'center');
								/* 渲染表单 */
								form.render();							
							},
							btn1 : function(index, layero) {
								var variables = {};
								 variables['approvingOpinion'] = $('#approvingOpinionText').val();
								 if($('#approvingOpinionText').val() != ""){
									 addVariables(variables, taskIdStr, processInstanceIdStr);
								 }	
								var json = {};
								json["task_id"] = data.ID_;
								json["assignee"] = $('#departmentStaffSelect option:selected').val();
								json["department"] = $('#departmentSelect option:selected').val();
								json["approval"] = $('#transferSelect option:selected').val();
								if(isEnd){
									
								}else{
									//限制输入框中不能用空值
								     if($('#departmentSelect option:selected').val()==""){
								    	 if(result.isDepartment){
								    		 layer.msg("请选择一个部门");
									    	 return false;
								    	 }								    	 
								     }	
								     if($('#departmentStaffSelect option:selected').val() == ""){
								    	 if(!result.isDepartment){
								    		 layer.msg("请选择移交人");
									    	 return false;	    		 
								    	 }
								     }	
								}														     
								$.ajax({
									type : "POST",//方法类型
									dataType : "json",//预期服务器返回的数据类型
									url : "../../activiti/finishTaskTwo",//url
									contentType: "application/json; charset=utf-8",
									data : JSON.stringify(json),
									success : function(result) {
										if (result.code == 0) {
											layer.close(index);
											layer.msg('通过成功');
											table.reload('userReload');
										}
									},
									error : function() {
										layer.msg('通过失败');
										layer.close(index);
									}
								});
							},
							btn2: function(index, layero){
								 var variables = {};
								 variables['approvingOpinion'] = $('#approvingOpinionText').val();
								 if($('#approvingOpinionText').val() != ""){
									 addVariables(variables, taskIdStr, processInstanceIdStr);
								 }							     
								layer.open({
									type : 1,
									title : "审批",
									skin : "layui-layer-lan",
									area : [ "40%" ],
									btn :  [ '确定','取消' ],
									content : $("#SelectApprovalDiv"),
									success : function(layero) {
										var btn = layero.find('.layui-layer-btn');
										btn.css('text-align', 'center');
										/* 渲染表单 */
										form.render();							
									},
									btn1:function(index,layero){
										var json = {};
										json["task_id"] = data.ID_;
										json["assignee"] = "";
										json["approval"] = $("#approvalSelect option:selected").val();
										$.ajax({
											type : "POST",//方法类型
											dataType : "json",//预期服务器返回的数据类型
											url : "../../activiti/finishTaskTwo",//url
											contentType: "application/json; charset=utf-8",
											data : JSON.stringify(json),
											success : function(result) {
												if (result.code == 0) {
													layer.close(index);
													layer.msg('驳回成功');
													table.reload('userReload');
												}
											},
											error : function() {
												layer.msg('驳回失败');
												layer.close(index);
											}
										});
									}	,
									btn2: function(index,layero){
										layer.close(index);
									}
								});
								
							}
						});
					} else if (data.NAME_.indexOf("分发") != -1) {//如果节点有分发二字就为并行分发节点
						
						$('#distributionForm').html("");
						$.each(transfer, function(index, data1) {
							$('#distributionForm').append('<div class="layui-form-item" style="margin-top: 15px">'
									+'<label class="layui-form-label">分发节点：</label>'
									+'<div class="layui-input-inline">'
									+'<input type="text" id="' + data1.taskName + '" value="' + data1.taskName + '" class="layui-input">'
									+'</div>'
									+'<label class="layui-form-label">接收人：</label>'
									+'<div class="layui-input-inline">'
									+'<select  id="'+ data1.condition +'"></select>'
									+'</div>'
									+'</div>');
							
							 $.ajax({
				    			 type: "post", 
				    			 url:"../../sysrole/departmentStaffSelection?departmen_id="+data.department+"&isNextApprovel="+ ($('#transferSelect option:selected').text().indexOf("审批") != -1 ? "0" : "1"),
				    			 async : false,
				    		     success:function(data){	
				    		    	 var optionstring = ""; 
					    	            $.each(data.sysuser, function(i,item){
					    	                optionstring += "<option value=\"" + item.id + "\" >" + item.name + "</option>";
					    	            });
					    	            $("#" + data1.condition).html('<option value=""></option>' + optionstring);  
				    		     }
				    		 });
						});
						/* 再弹出编辑界面 */
						layer.open({
							type : 1,
							title : "分发任务",
							skin : "layui-layer-lan",
							area : [ "54%" ],
							btn : ["分发","取消"],
							content : $("#distribution"),
							success : function(layero) {
								$('#BrancheCurrentNode').val(data.NAME_);
								var btn = layero.find('.layui-layer-btn');
								btn.css('text-align', 'center');
								/* 渲染表单 */
								form.render();							
							},
							btn1 : function(index, layero) {
								for(var i = 0; i < transfer.length; i++){
									//document.getElementById(transfer[i].condition).value
									
									transfer[i].Assignee = $("select#" + transfer[i].condition ).val();
									//限制输入框中不能用空值
								     if($("select#" + transfer[i].condition ).val() == ""){
								    	 if(!result.isDepartment){
								    		 layer.msg("请选择移交人");
									    	 return false;	    		 
								    	 }
								     }	
								}
								var json = {};
								json["task_id"] = data.ID_;
								json["transfer"] = transfer;
								
								$.ajax({
									type : "POST",//方法类型
									dataType : "json",//预期服务器返回的数据类型
									url : "../../activiti/finishTaskBranche",//url
									contentType: "application/json; charset=utf-8",
									data : JSON.stringify(json),
									success : function(result) {
										if (result.code == 0) {
											layer.close(index);
											layer.msg('通过成功');
											table.reload('userReload');
										}
									},
									error : function() {
										layer.msg('通过失败');
										layer.close(index);
									}
								});
							}
						});
					}else {
						$('#approvingOpinionDiv').css('display','none');
						/* 再弹出编辑界面 */
						layer.open({
							type : 1,
							title : "移交流程",
							skin : "layui-layer-lan",
							area : [ "45%" ],
							btn : isEnd == true ? [ '完成']:[ '移交'],
							content : $("#approvalPopup"),
							success : function(layero) {
								var btn = layero.find('.layui-layer-btn');
								btn.css('text-align', 'center');																
								/* 渲染表单 */
								form.render();
							},
							yes : function(index, layero) {
								var json = {};
								json["task_id"] = data.ID_;
								json["assignee"] = $('#departmentStaffSelect option:selected').val();
								json["department"] = $('#departmentSelect option:selected').val();
								json["approval"] = $('#transferSelect option:selected').val();
								
                                if(isEnd){
									
								}else{
									//限制输入框中不能用空值
								     if($('#departmentSelect option:selected').val()==""){
								    	 if(result.isDepartment){
								    		 layer.msg("请选择一个部门");
									    	 return false;
								    	 }	
								     }	
								     if($('#departmentStaffSelect option:selected').val() == ""){
								    	 if(!result.isDepartment){
								    		 layer.msg("请选择移交人");
									    	 return false;	    		 
								    	 }
								     }	
								}
								$.ajax({
									type : "POST",//方法类型
									dataType : "json",//预期服务器返回的数据类型
									url : "../../activiti/finishTaskTwo",//url
									contentType: "application/json; charset=utf-8",
									data : JSON.stringify(json),
									success : function(result) {
										if (result.code == 0) {
											layer.close(index);
											layer.msg('通过成功');
											table.reload('userReload');
										}
									},
									error : function() {
										layer.msg('通过失败');
										layer.close(index);
									}
								});
							}
						});
					}
					
				},
				error : function() {
					layer.msg('通过失败');
					layer.close(index);
				}
			});
			
		} else if (obj.event === 'operationRecord') {
			var processInstanceId =  data.processInstanceId;
			layer.open({
				type : 1,
				area : [ "575px", '400px' ],
				title : "审批流程",
				id : "haha",
				maxmin : false,
				content : '<div><table id="templateTable"></table></div>',
				success : function(index, layero) {
					table.render({
						elem : '#templateTable',
						width : '100%',
						url : '../../activiti/operationRecord?processInstanceId=' + processInstanceId,// 数据接口、
						cols : [ [ // 表头
						{
							field : 'assignee',
							title : '操作人',
							width : 100,
							fixed : 'left',
							unresize : true,
							align : 'center'
						}, {
							field : 'activityName',
							width : 150,
							title : '流程节点',
							align : 'center'
						}, {
							field : 'startTime',
							width : 160,
							title : '开始时间',
							align : 'center'
						}, {
							field : 'endTime',
							width : 160,
							title : '结束时间',
							align : 'center'
						}, ] ]
					});
				}
			});
		}
	 else if (obj.event === 'operationRecord') {
			var processInstanceId =  data.processInstanceId;
			layer.open({
				type : 1,
				area : [ "575px", '400px' ],
				title : "审批流程",
				id : "haha",
				maxmin : false,
				content : '<div><table id="templateTable"></table></div>',
				success : function(index, layero) {
					table.render({
						elem : '#templateTable',
						width : '100%',
						url : '../../activiti/operationRecord?processInstanceId=' + processInstanceId,// 数据接口、
						cols : [ [ // 表头
						{
							field : 'assignee',
							title : '操作人',
							width : 100,
							fixed : 'left',
							unresize : true,
							align : 'center'
						}, {
							field : 'activityName',
							width : 150,
							title : '流程节点',
							align : 'center'
						}, {
							field : 'startTime',
							width : 160,
							title : '开始时间',
							align : 'center'
						}, {
							field : 'endTime',
							width : 160,
							title : '结束时间',
							align : 'center'
						}, ] ]
					});
				}
			});
		}
	});

	$('.userTable .layui-btn').on('click', function() {
		var type = $(this).data('type');
		active[type] ? active[type].call(this) : '';
	});

	
	function projectDelete(id) {
		$.ajax({
			url : '../../activiti/delectExample?processInstanceId=' + id,
			contentType : "application/json;charset=utf-8",
			type : 'post',
			success : function(data) {
				var json = JSON.parse(data);
				if (json.code == '0') {
					layer.msg('删除项目成功');
				} else {
					layer.msg('删除项目失败');
				}
			}
		})
	}

	
	
	//选完文件后不自动上传
	 var uploadListIns = upload.render({
	    elem: '#upLoadCalibrationDataLayerBtn'
	    ,url: '../../upLoadFile/uploadCalibrationDataFile'
	    ,auto: false
	    ,accept: 'file'
	    ,data: {processInstanceId: function(){
	        return processInstanceIdStr;
	    }, taskId : function(){
	    	return taskIdStr;
	    }}
	    ,exts: 'xls|xlsx|pptx|ppt|doc|docx|pdf|txt'
	    ,multiple: true
	    ,bindAction: '#addCalibrationDataLayerBtn'
	    ,choose: function(obj){	 
	    	var  files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
	    	 var uploadFileNameUl = $('#uploadFileNameUl');
	    	  obj.preview(function(index, file, result){
	    		  var exist = validateFileExist(file.name, taskIdStr);
	    		  if(exist == "1"){
	    			  layer.confirm("<strong>" +file.name +'</strong>文件已存在，是否要继续提交并覆盖已存在文件？', {btn: ['是','否'] ,cancel: function(index1, layero) {
	    				  delete files[index];
	    				  layer.close(index1);
	    			   }},function(index1){
	    				   var li =  $(["<li class='clickLi' id='upload"+ index +"'>"+ file.name + "</li>"].join(''));
	    				   uploadFileNameUl.append(li)
	    				   var btn2 = document.getElementById('upload' + index);
	    				   btn2.addEventListener('click', function(){
	    					   $('#upload'+ index).remove();
	    					   delete files[index];
	    				   }, false);		    				   
		    			   layer.close(index1);
	    			   },function(index1){
	    				   delete files[index];
	    				   layer.close(index1);
	    			   });
	    		  }else{	    			  
	    			  var li =  $(["<li class='clickLi' id='upload"+ index +"'>"+ file.name + "</li>"].join(''));
   				   uploadFileNameUl.append(li)
   				   var btn2 = document.getElementById('upload' + index);
   				   btn2.addEventListener('click', function(){
   					   $('#upload'+ index).remove();
   					   delete files[index];
   				   }, false);	
	    		  }	    		  
	    	  });
	    }
	    ,done: function(res,index,upload){
	    	if(res.code == 0){ 
	    		delete this.files[index];
	    		$('#upload'+ index).remove();
	    	}else{
	    		return this.error(index, upload);
	    	}
	    	var attachments = {};
	    	attachments['filePath'] = res.filePath;
	    	attachments['fileName'] = res.fileName;
            addAttachments(attachments, taskIdStr, processInstanceIdStr);
	    }
	    ,allDone: function(obj){ //当文件全部被提交后，才触发
	    	$("#processInstanceHistroyRecordUl").empty();
			$("#formCalibrationDataRemarksText").val("");
			 //$('#uploadFileNameUl').empty();//清空文件ul
			showHistoryRecord(processInstanceIdStr);
	      }
	  ,error: function(res,index,upload){
		  delete this.files[index];
		  uploadListIns.config.elem.next()[0].value = ''; 
		  layer.msg(res.fileName + "文件上传失败");
	  }
	  });
	  
	    //点击上传标定数据文件
		$("#formCancelLayerBtn").click(function(){
			$('#formCalibrationDataRemarksText').val("");
			 layer.close(layerIndex);
		 });
		
		//点击上传标定数据文件
		$("#addCalibrationDataLayerBtn").click(function(){
			 var variables = {};
			 variables['remarks'] = $('#formCalibrationDataRemarksText').val();
			 if($('#formCalibrationDataRemarksText').val() == ""){
				 layer.msg("请输入备注");
				 return false;
			 }
		     addVariables(variables, taskIdStr, processInstanceIdStr);
		     $("#processInstanceHistroyRecordUl").empty();
				$("#formCalibrationDataRemarksText").val("");
				 //$('#uploadFileNameUl').empty();//清空文件ul
		     showHistoryRecord(processInstanceIdStr);
		 });
	
	

	//监听姓名的输入框
    $('#nameText').on("input propertychange", function() {
        active.reload();
    });
  //监听姓名的输入框
    $('#numberText').on("input propertychange", function() {
        active.reload();
    });
      
    
   form.render('select');
   
   /**添加变量（备注等）*/
   function addVariables(variables, taskId, processInstanceIdStr){
	   var json = {}; 
	   json["variables"] = variables;
	   json["taskId"] = taskId;
	   json['aprroveingOpinion'];
	   json["processInstanceId"] = processInstanceIdStr;
	   $.ajax({ 
	       type: "post", 
	       url: "../../activiti/addVariables", 
	       contentType: "application/json; charset=utf-8",
	       dataType: "json",
	       async: false,
	       data: JSON.stringify(json), 
	       success: function(data){
	    	   if(data.code == "0"){
		    		  $("#processInstanceHistroyRecordUl").empty();
		  			$("#formCalibrationDataRemarksText").val("");
		  			 //$('#uploadFileNameUl').empty();//清空文件ul
		  			showHistoryRecord(processInstanceIdStr);
		    	  }else{
		    		  layer.msg("添加失败");
		    	  }
	       } 
		});
   }
   
   /**添加附件*/
   function addAttachments(attachments, taskId, processInstanceIdStr){
	   var json = {}; 
	   json["attachments"] = attachments;
	   json["taskId"] = taskId;
	   json["processInstanceId"] = processInstanceIdStr;
	   $.ajax({ 
	       type: "post", 
	       url: "../../activiti/addAttachments", 
	       contentType: "application/json; charset=utf-8",
	       dataType: "json",
	       async:false,
	       data: JSON.stringify(json), 
	       success: function(data){
	    	  if(data.code == "0"){

	    	  }else{	    		  
	    		  layer.msg("添加附件失败");
	    	  }
	       } 
		});
   }
   
   /**展示历史节点记录*/
   function showHistoryRecord(processInstanceId){
	   var json = {}; 
	   json["processInstanceId"] = processInstanceId;
	   $.ajax({ 
	       type: "post", 
	       url: "../../activiti/findProcessInstanceHistoryRecord", 
	       contentType: "application/json; charset=utf-8",
	       dataType: "json",
	       async:false, 
	       data: JSON.stringify(json), 
	       success: function(result){
	    	  var processInstanceHistroyRecordUl = $("#processInstanceHistroyRecordUl");
	    	  var data = result.data;
	    	  for(var i=0;i<data.length;i++){	
	    		  processInstanceHistroyRecordUl.append(" <li class='layui-timeline-item' > <i class='layui-icon layui-timeline-axis'>&#xe63f;</i><div class='layui-timeline-content layui-text' id='histroyRecordUlDiv"+ i + "'></div></li>");
	    		  var histroyRecordUl = $("#histroyRecordUlDiv" + i);
	    		  var approval = data[i].approval;
	    		  if(approval == null || approval == ""){
	    			  approval = "";
	    		  }else{
	    			  if(approval == "0"){
	    				  approval = "通过";
	    			  }else{
	    				  approval = "<font color='red'>不通过</font>";
	    			  }
	    		  }	    		  
	    		  histroyRecordUl.append(" <h3 class='layui-timeline-title'><font color='#00AEAE'>" + data[i].taskName + "&nbsp;&nbsp;&nbsp;&nbsp;"+ data[i].assignee +"&nbsp;&nbsp;&nbsp;&nbsp;" + approval +"</font></h3>");
	    		  histroyRecordUl.append("<strong>时间：</strong>" + data[i].taskStartTime);
	    		  var attachments = data[i].attachments;
	    		  if(attachments.length > 0){
	    			  for(var j = 0;j < attachments.length; j++){
	    				  if(j == 0){
	    					  histroyRecordUl.append("</br><strong>附件：</strong>");
	    				  }	    				  
	    				  if(j == attachments.length-1){
	    					  histroyRecordUl.append("&nbsp;&nbsp;【<a href='javascript:showAttachments(\"" + attachments[j].url + "\");'>" + attachments[j].name + "</a>】" + "&nbsp;&nbsp;");
	    					  var btnIcon = "&#xe601;";
	    					  if(i == data.length-1){
	    						  btnIcon = "&#xe642;";
	    					  }
	    					  histroyRecordUl.append("<a href='javascript:showTaskAttachmentsTable(" + data[i].taskId +")' class='layui-btn layui-btn-xs'><i class='layui-icon'>" + btnIcon + "</i></a>");
	    				  }else{
	    					  histroyRecordUl.append("&nbsp;&nbsp;【<a href='javascript:showAttachments(\"" + attachments[j].url + "\");'>" + attachments[j].name + "</a>】&nbsp;");
	    				  }
	    			  }
	    		  }
	    		  var remarks = "";
	    		  if(data[i].remarks != null && data[i].remarks != ""){
	    			  if(i == data.length-1){
	    				  $('#formCalibrationDataRemarksText').val(data[i].remarks);
	    			  }
	    			  remarks = data[i].remarks
	    			  histroyRecordUl.append("</br><strong>备注：</strong>" + remarks );
	    		  }	    		  
	    		  if(data[i].approvingOpinion != null && data[i].approvingOpinion != ""){
	    			 var  approvingOpinion = data[i].approvingOpinion
	    			  histroyRecordUl.append("</br><strong><font color='blue'>审批意见：</font></strong>" + approvingOpinion );
	    		  }
	    		  
	    	  }	    	  
	       } 
		});
   }
   
   
   //节点附件的表格
   table.render({
	   elem: '#taskAttachmentsTable',
	   url: '../../activiti/findTaskAttachmentsTable',
	   page: false,
	   cols: [[
		   {type : 'checkbox',	fixed : 'left'},
		   {field: 'name', title: '文件名称',width: 345},
		   {field: 'time', title: '提交时间',width: 345,templet:function(d){return datetimeFormat(d.time)}},
		   {field : 'url', hide  : true},
		   { title: '操作', toolbar : '#barAttachments', width: 150 }
	   ]],
	   done : function() {	
	   },
	   id:'attachmentsReload'
   });
   
    //监听行工具事件
	table.on('tool(taskAttachmentsTable)', function(obj) {
		var data = obj.data;
		if (obj.event === 'del') {
		} else if (obj.event === 'downLoad') {		
			 downLoadFile(data.name,data.url);
		}
	});
   
   
   
   /**
    * html页面调用js文件里的函数，写法必须为  方法名 = function (){}形式，其他方式写，html页面会搜索不到该函数，就会报错。
    *  报错类型 ： function 方法名(){}   和  var 方法名 = function(){}
    * */
   showTaskAttachmentsTable =  function (taskId){
	   table.reload('attachmentsReload',{
			where: { //设定异步数据接口的额外参数，任意设
			    taskId: taskId
			  }
		});
	   if(taskId == taskIdStr){
		   $('#deleteAttachmentsBtn').show();
	   }else{
		   $('#deleteAttachmentsBtn').hide();
	   }
		layer.open({
			type : 1,
			title : "附件列表",
			skin : "layui-layer-lan",
			offset: '150px',
			shadeClose : true,
			area : "900px",
			//maxWidth: 1000,
			maxHeight: 400,
			content : $("#taskAttachmentsTableDiv"),
			toolbar: true 
		});	  
   }
   
   
   //根据附件id删除附件
    deleteAttachmentsById = function (){
       var json = {};
	   var attachments = table.checkStatus('attachmentsReload').data;
	   json['attachments'] = attachments;
	   if(attachments.length < 1){
		   layer.msg("请至少选择一个文件");
		   return false;
	   }
	   layer.confirm('真的删除此文件吗？', function(index) {
		   $.ajax({ 
		       type: "post", 
		       url: '../../activiti/deleteAttachmentById', 
		       contentType: "application/json; charset=utf-8",
		       data: JSON.stringify(json),
		       success: function(data){
		    	   if(data.code == "0"){
		    		   layer.msg("删除成功");
		    		   table.reload('attachmentsReload');
			    	   $("#processInstanceHistroyRecordUl").empty();
						$("#formCalibrationDataRemarksText").val("");
						showHistoryRecord(processInstanceIdStr);
		    	   }else{
		    		   layer.msg("删除失败");
		    		   table.reload('attachmentsReload');
		    	   }
		       }
		   }); 
		});
   }
   
   //下载多个文件并打包成zip
   downLoadMutilFilesToZip = function(){
           var list = table.cache.attachmentsReload;
           var imgNameList = [];
           var imgUrlList = [];
           for(var i = 0;i<list.length;i++){
               imgNameList.push(list[i].name);//文件名称
               imgUrlList.push(list[i].url);//文件绝对路径
           }
           var paths =  encodeURI(encodeURI(imgUrlList));
           var names = encodeURI(encodeURI(imgNameList));
           //将名称传入后台
           window.location.href = "../../upLoadFile/downLoadMutilFilesToZip?names="+names+"&paths="+paths;
   }
   
   //验证上传的文件在这个任务节点是否已经存在
   function validateFileExist(fileName, taskId){
	   var result = "0";
	   $.ajax({ 
	       type: "post", 
	       url: "../../upLoadFile/validateFileExist", 
	       async:false, 
	       data: {fileName: fileName, taskId:taskId}, 
	       success: function(data){
	    	   result = data;
	       }
	   }); 
	   return result;
   }
   
   showAttachments = function(url){
	   url = url.substring(0,url.lastIndexOf(".")) + ".pdf";
	   url = url.substring(url.indexOf("uploadFile")-1);
	   alert(url);
	   PDFObject.embed(url,"#pdf_preview");
	   $.ajax({ 
	       type: "post", 
	       url: "../../upLoadFile/officeToPdf", 
	       async:false, 
	       data: {url:url}, 
	       success: function(data){
	    	   result = data;
	       }
	   }); 
	   layer.open({
			type : 1,
			title : "附件列表",
			skin : "myskin",
			shadeClose : true,
			area : ["70%","90%"],
			content : $("#pdf_preview"),
			toolbar : true 
		});	   
   }
  
   
   //全局文件的表格
   table.render({
	   elem: '#globalFileTable',
	   url: '../../activiti/findGlobalFIleTableByPid',
	   page: false,
	   cols: [[
		   {field: 'fileName', title: '文件名称'},
		   {field: 'time', title: '更新时间',templet:function(d){return datetimeFormat(d.time)}},
		   {field: 'name', title: '操作人' , width: 100},
		   {field : 'url', hide  : true},
		   { title: '操作', width: 200 ,templet: function(d){
			   if(isUpload){
				   return "<a class='layui-btn layui-btn-normal layui-btn-xs' lay-event='edit' style='margin-left: 15px;'>编辑</a>"+
			        "<a class='layui-btn layui-btn-xs' lay-event='downLoadGlobalFile' style='margin-left: 15px;'>下载</a>"+
			        "<a class='layui-btn layui-btn-xs layui-btn-danger' lay-event='delete' style='margin-left: 15px;'>删除</a>"	;
			   }else{
				   return "<a class='layui-btn layui-btn-xs' lay-event='downLoadGlobalFile' style='margin-left: 15px;'>下载</a>";
			   }
		   }}
	   ]],
	   done : function() {	
	   },
	   id:'globalFileTableReload'
   });
   
   
   //监听行工具事件
	table.on('tool(globalFileTable)', function(obj) {
		var data = obj.data;
		processInstanceFileIdStr = data.id;
		if (obj.event === 'edit') {
			 layer.open({
					type : 1,
					title : "文件历史版本",
					skin : "editFile",
					offset: '150px',
					shadeClose : true,
					area : "900px",
					//maxWidth: 1000,
					maxHeight: 400,
					content : $("#singleglobalFileTableDiv"),
					toolbar: true 
				});	
			 table.reload('singleGlobalFileHisReload',{
					where: { //设定异步数据接口的额外参数，任意设
						processInstanceFileId: data.id
					  }
			    });
		} else if (obj.event === 'downLoadGlobalFile') {	
			 downLoadFile(data.fileName,data.url);
		} else if (obj.event === 'delete'){
			 layer.confirm('真的删除此文件吗？', function(index) {
				     var json = {};
					json["id"] = data.id;
					json["url"] = data.url;
				   $.ajax({ 
				       type: "post", 
				       url: '../../activiti/deleteGlobalFile',
				       contentType: "application/json; charset=utf-8",
				       data: JSON.stringify(json),
				       success: function(data){
				    	   if(data == 1){
				    		   layer.msg("删除成功");
				    		   obj.del();
				    	       layer.close(index);
				    	   }else{
				    		   layer.msg("删除失败");
				    	   }
				       }
				   }); 
				});
		}
	});
 
	  //多文件列表示例
	  var demoListView = $('#demoList')
	  ,uploadListIns = upload.render({
	    elem: '#testList'
	    ,url: '../../upLoadFile/uploadGlobalFile'
	    ,accept: 'file'
	    //,exts: 's19|mot|a2l|map|hex'
	    ,data: {processInstanceId: function(){
	        return processInstanceIdStr;
	    }, taskId : function(){
	    	return taskIdStr;
	    }}
	    ,multiple: true
	    ,auto: false
	    ,bindAction: '#testListAction'
	    ,choose: function(obj){   
	      var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
	      //读取本地文件
	      obj.preview(function(index, file, result){
	        var tr = $(['<tr id="upload-'+ index +'">'
	          ,'<td>'+ file.name +'</td>'
	          ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>'
	          ,'<td>等待上传</td>'
	          ,'<td>'
	            ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
	            ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
	          ,'</td>'
	        ,'</tr>'].join(''));
	        
	        //单个重传
	        tr.find('.demo-reload').on('click', function(){
	          obj.upload(index, file);
	        });
	        
	        //删除
	        tr.find('.demo-delete').on('click', function(){
	          delete files[index]; //删除对应的文件
	          tr.remove();
	          uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
	        });
	        
	        demoListView.append(tr);
	      });
	    }
	    ,done: function(res, index, upload){
	      if(res.code == 0){ //上传成功
	        var tr = demoListView.find('tr#upload-'+ index)
	        ,tds = tr.children();
	        tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
	        tds.eq(3).html(''); //清空操作
	        table.reload('globalFileTableReload',{
				where: { //设定异步数据接口的额外参数，任意设
					processInstanceId: processInstanceIdStr
				  }
		    });
	        if(res.fileType == "s19"){
	        	layer.msg(res.msg);
	        }
	        return delete this.files[index]; //删除文件队列已经上传成功的文件	        
	      }else if(res.code == 2){
	    	  layer.msg(res.msg);
	      }
	      this.error(index, upload);
	    }
	    ,error: function(index, upload){
	      var tr = demoListView.find('tr#upload-'+ index)
	      ,tds = tr.children();
	      tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
	      tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
	    }
	  });
	  
	  showUploadGlobalFileTable = function(){
		  layer.open({
				type : 1,
				title : "上传全局文件",
				skin : "editFile",
				offset: '100px',
				shadeClose : true,
				area : ["60%","70%"],
				content : $("#uploadGlobalFileListDiv"),
				toolbar: true 
			});	
	  }
	  
	  
	  //全局文件的表格
	   table.render({
		   elem: '#singleGlobalFileHisTable',
		   url: '../../activiti/findSingleGlobalFIleHisTableById',
		   page: false,
		   cols: [[
			   {field: 'filename', title: '文件名称'},
			   {field: 'time', title: '上传时间',templet:function(d){return datetimeFormat(d.time)}},
			   {field: 'name', title: '操作人' , width: 100},
			   {field : 'url', hide  : true},
			   { title: '操作', toolbar : '#barSingleGlobalFile', width: 150 }
		   ]],
		   done : function() {	
		   },
		   id:'singleGlobalFileHisReload'
	   });
	   
	    //监听行工具事件
		table.on('tool(singleGlobalFileHisTable)', function(obj) {
			var data = obj.data;
			if (obj.event === 'downLoad') {					
				 downLoadFile(data.filename,data.url);
			}
		});
		
		   //下载多个文件并打包成zip
		downLoadGlobalMutilFilesToZip = function(){
		           var list = table.cache.singleGlobalFileHisReload;
		           var imgNameList = [];
		           var imgUrlList = [];
		           for(var i = 0;i<list.length;i++){
		               imgNameList.push(list[i].filename); 
                        //压缩文件不允许重名，故有重名文件则改变名字        
			           for(var j = 0; j < i; j++){
			        	   if(list[i].filename == list[j].filename){
			        		   imgNameList[i] = list[i].filename.substr(0,list[i].filename.indexOf(".")) + "_" +  i + list[i].filename.substr(list[i].filename.indexOf(".")) ;//文件名称
			        		   break;
			        	   }
			           }
		               imgUrlList.push(list[i].url);//文件绝对路径
		           }
		           var paths =  encodeURI(encodeURI(imgUrlList));
		           var names = encodeURI(encodeURI(imgNameList));
		           //将名称传入后台
		           window.location.href = "../../upLoadFile/downLoadMutilFilesToZip?names="+names+"&paths="+paths;
		   }
	   
		//选完文件后不自动上传
		  upload.render({
		    elem: '#test8'
		    ,url: '../../upLoadFile/uploadGlobalFile'
	    	,accept: 'file'
    	    ,data: {processInstanceFileId: function(){
    	        return processInstanceFileIdStr;
    	    }, taskId : function(){
    	    	return taskIdStr;
    	    },processInstanceId : function(){
    	    	return processInstanceIdStr;
    	    }}
		    ,auto: false
		    //,multiple: true
		    ,bindAction: '#test9'
		    ,done: function(res){
		    	if(res.code=="0"){
		    		layer.msg("添加成功");
		    	}else{
		    		this.error(index, upload);
		    	}	
		    	table.reload('singleGlobalFileHisReload');
		    	table.reload('globalFileTableReload');
		    }
		    ,error:function(res){
		    	 layer.msg("添加失败");
		    }
		  });
		  
		  showPlatFileTable = function(){
			  table.render({
					elem : '#platProcessInstanceTable',
					url : '../../plat/selectPlatProcessInstanceByPlatId?processInstanceId='+ processInstanceIdStr + "&type=" + type,	  
					title : '任务表',
					cols : [ [ 
					    	{field: 'id',title: 'ID',sort: true, fixed: 'left'},
					    	{field: 'name',title: '版本名称'},
					    	{fixed : 'right',title : '操作',toolbar : '#barPlatProcessInstance',width : 150}
				           ] ],
			        page: false,
				    id: 'platProcessInstanceTableReload'
				});	
			  layer.open({
					type : 1,
					title : "最新平台程序版本",
					skin : "layui-layer-lan",
					shadeClose : true,
					area : ["50%", "30%"],
					content : $("#platProcessInstanceTableDiv") 
				});				  
		  }
		  
		//监听行工具事件
			table.on('tool(platProcessInstanceTable)', function(obj) {
				var data = obj.data;
				if (obj.event === 'details') {
					 table.reload('platProcessInstanceFileTableReload',{
							where: { //设定异步数据接口的额外参数，任意设
								processInstanceId: data.processInstanceId
							  }
					 });
					 layer.open({
							type : 1,
							title : "平台文件列表",
							skin : "layui-layer-lan",
							shadeClose : true,
							area : ["60%", "80%"],
							content : $("#platProcessInstanceFileTableDiv") 
						});	
				}else if(obj.event === 'attachments'){
					table.reload('attachmentsTableReload',{
						where: { //设定异步数据接口的额外参数，任意设
							processInstanceId : data.processInstanceId
						  }
					 });
					 layer.open({
							type : 1,
							title : "附件文件列表",
							skin : "layui-layer-lan",
							shadeClose : true,
							area : ["60%", "80%"],
							//maxWidth: 1000,
							//maxHeight: $(window).height()*0.8,
							content : $("#attachmentsTableDiv") 
						});	
				} 
			});
			
			table.render({
				elem : '#platProcessInstanceFileTable',
				url : '../../plat/findPlatProcessInstanceFileTableByPid',
				title : '任务表',
				cols : [ [ 
				    	{field: 'id',title: 'ID',sort: true, fixed: 'left',width : 100},
				    	{field: 'fileName',title: '文件名称'},
				    	{field: 'time',title: '时间',templet:function(d){return datetimeFormat(d.time)},width : 200},
				    	{field: 'name',title: '更新人',width : 100},
				    	{fixed : 'right',title : '操作',toolbar : '#barPlatProcessInstanceFile',width : 100}
			           ] ],
		        page: false,
			    id: 'platProcessInstanceFileTableReload'
			});
			
			//监听行工具事件
			table.on('tool(platProcessInstanceFileTable)', function(obj) {
				var data = obj.data;
				if (obj.event === 'downLoad') {
					downLoadFile(data.fileName, data.url);
				} 
			});
			
			table.render({
				elem : '#attachmentsTable',
				url : '../../project/findattachmentsTableByPid',
				title : '文件的附件',
				cols : [ [ 
						//{type : 'checkbox', fixed: 'left'},
				    	{field: 'name',title: '文件名称'},
				    	{field: 'time',title: '更新时间',sort: true,templet:function(d){return datetimeFormat(d.time)},width : 250},
				    	{field: 'description',title: '更新人',width : 150},
				    	{fixed : 'right', title : '操作', toolbar : '#barAttachments', width : 150}
			           ] ],
		        page: false,
			    id: 'attachmentsTableReload',
			});
			
			//监听行工具事件
			table.on('tool(attachmentsTable)', function(obj) {
				var data = obj.data;
				if (obj.event === 'downLoad') {
					 downLoadFile(data.name, data.url);
				}
			});
		  
			downLoadplatProcessInstanceFileToZip = function(){
				  var list = table.cache.platProcessInstanceFileTableReload;
		           var imgNameList = [];
		           var imgUrlList = [];
		           for(var i = 0;i<list.length;i++){    
			           imgNameList.push(list[i].fileName); 
			           //压缩文件不允许重名，故有重名文件则改变名字        
		               for(var j = 0; j < i; j++){
		            	   if(list[i].fileName == list[j].fileName){
		            		   imgNameList[i] = list[i].fileName.substr(0,list[i].fileName.indexOf(".")) + "_" +  i + list[i].fileName.substr(list[i].fileName.indexOf(".")) ;//文件名称
		            		   break;
		            	   }
		               }
		               imgUrlList.push(list[i].url);//文件绝对路径
		           }
		           var paths =  encodeURI(encodeURI(imgUrlList));
		           var names = encodeURI(encodeURI(imgNameList));
		           //将名称传入后台
		           window.location.href = "../../upLoadFile/downLoadMutilFilesToZip?names="+names+"&paths="+paths;
			}
			
			downLoadAttachmentsFilesToZip = function(){
				var list = table.cache.attachmentsTableReload;
				           var imgNameList = [];
				           var imgUrlList = [];
				           for(var i = 0;i<list.length;i++){    
					           imgNameList.push(list[i].name); 
					           //压缩文件不允许重名，故有重名文件则改变名字        
				               for(var j = 0; j < i; j++){
				            	   if(list[i].name == list[j].name){
				            		   imgNameList[i] = list[i].name.substr(0,list[i].name.indexOf(".")) + "_" +  i + list[i].name.substr(list[i].name.indexOf(".")) ;//文件名称
				            		   break;
				            	   }
				               }
				               imgUrlList.push(list[i].url);//文件绝对路径
				           }
				           var paths =  encodeURI(encodeURI(imgUrlList));
				           var names = encodeURI(encodeURI(imgNameList));
				           //将名称传入后台
				           window.location.href = "../../upLoadFile/downLoadMutilFilesToZip?names="+names+"&paths="+paths;
			}
			
			downLoadProgramFilesToZip = function(){
				var list = table.cache.globalFileTableReload;
				           var imgNameList = [];
				           var imgUrlList = [];
				           for(var i = 0;i<list.length;i++){    
					           imgNameList.push(list[i].fileName); 
					           //压缩文件不允许重名，故有重名文件则改变名字        
				               for(var j = 0; j < i; j++){
				            	   if(list[i].fileName == list[j].fileName){
				            		   imgNameList[i] = list[i].fileName.substr(0,list[i].fileName.indexOf(".")) + "_" +  i + list[i].fileName.substr(list[i].fileName.indexOf(".")) ;//文件名称
				            		   break;
				            	   }
				               }
				               imgUrlList.push(list[i].url);//文件绝对路径
				           }
				           var paths =  encodeURI(encodeURI(imgUrlList));
				           var names = encodeURI(encodeURI(imgNameList));
				           //将名称传入后台
				           window.location.href = "../../upLoadFile/downLoadMutilFilesToZip?names="+names+"&paths="+paths;
			}
			
			//已读未读加载table的方法
		  findisProcessInstanceRead= function(status){
			  var nameText = $('#nameText');
				var numberText = $('#numberText');
				// 执行重载
				table.reload('userReload', {
					page : {
						curr : 1
					// 重新从第 1 页开始
					},
					where : {
						nameText : nameText.val(),
						numberText : numberText.val(),
						isProcessInstanceRead: status
					}
				});
				element.render('breadcrumb');
		  }
			
		  showMergeFileDiv = function(){
			  $("#platProcessInstanceSelectId").empty();
			  $("#projectProcessInstanceSelectId").empty();
			  $('#programFileNameInput').val('');
			  $('#dataFileNameInput').val('');
			  $('#programFileNameInput').css('color','black');
			  $('#dataFileNameInput').css('color','black');
			  $.ajax({
				  type:'post',
				  url:'../../plat/selectPlatProcessInstanceByProjectPid',
				  async: false,
				  data: {processInstanceId: processInstanceIdStr},
				  success: function(result){					  
					  var optionstring = ""; 
		              $.each(result.data, function(i,item){
		                  optionstring += "<option value=\"" + item.processInstanceId + "\" >" + item.version + "</option>";
		              });
		              $("#platProcessInstanceSelectId").html('<option value="">请选择版本</option>' + optionstring);   
				  }
			  });
			  $.ajax({
				  type:'post',
				  url:'../../project/findProjecProcessInstanceByProjectPid',
				  async: false,
				  data: {processInstanceId: processInstanceIdStr},
				  success: function(result){					  
					  var optionstring = ""; 
		              $.each(result.data, function(i,item){
		                  optionstring += "<option value=\"" + item.processInstanceId + "\" >" + item.version + "</option>";
		              });
		              $("#projectProcessInstanceSelectId").html('<option value="">请选择版本</option>' + optionstring);   
				  }
			  });
			  layer.open({
				  type:1,
				  title:"标定数据和程序文件绑定",
				  content: $('#mergeFileDiv'),
				  btn: ['绑定','取消'],
				  area: ['800px'],
				  success:function(layero){
					  var btn = layero.find('.layui-layer-btn');
						btn.css('text-align', 'center');
						/* 渲染表单 */
						form.render();
				  },
				  btn1:function(index,layero){
					  if($('#programFileNameInput').val() == ''){
						  layer.msg('程序文件为空');
						  return false;
					  }
					  if($('#programFileNameInput').attr("data-url") == ''){
						  layer.msg('程序文件路径不存在');
						  return false;
					  }
					  if($('#dataFileNameInput').val() == ''){
						  layer.msg('标定数据文件为空');
					  }
					  if($('#dataFileNameInput').attr("data-url") == ''){
						  layer.msg('标定数据文件路径不存在');
						  return false;
					  }
					  $.ajax({
						  type:'post',
						  url:'../../upLoadFile/mergeFile',
						  data: {
							  processInstanceId: processInstanceIdStr,
							  taskId: taskIdStr,
							  programFilePath: $('#programFileNameInput').attr("data-url"),
							  dataFilePath: $('#dataFileNameInput').attr("data-url"),
							  version: $('#platProcessInstanceSelectId option:selected').html()
						  },
						  success: function(result){
							  if(result == "success"){
								  table.reload('globalFileTableReload',{
										where: { //设定异步数据接口的额外参数，任意设
											processInstanceId: processInstanceIdStr
										  }
								    });
								  layer.msg('程序文件和标定数据绑定成功');
								  layer.close(index);
							  }else{
								  layer.msg('程序文件和标定数据绑定失败');
							  }	  
						  }
					  });
				  },
				  btn2:function(index,layero){
					  layer.close(index);
				  }
			  });
		  }
		  
		  
		  form.on('select(PlatProcessInstanceSelectFIlter)',function(data){
			  $('#programFileNameInput').val('');
			  $('#programFileNameInput').css('color','black');
			  $.ajax({
				   type:'post',
				   url:'../../plat/findPlatProcessInstanceFileTableByPid',
				   data:{processInstanceId: data.value},
				   success: function(result){
					   var data = result.data;
					   if(data != null){
						   $.each(data,function(i,item){
							   var fileName = item.fileName;
							  if(fileName.substr(fileName.lastIndexOf('.')) == ".mot" || fileName.substr(fileName.lastIndexOf('.')) == ".s19"){								  
								  $('#programFileNameInput').val(fileName);
								  $('#programFileNameInput').attr("data-url", item.url);
								  return false;
							  } 							  
						   });
						   if($('#programFileNameInput').val()==''){
							   $('#programFileNameInput').css('color','red');
							   $('#programFileNameInput').val("* 未找到程序文件,请到平台管理页面进行确认");
							   
						   }
					   }else{ 
						   $('#programFileNameInput').css('color','red');
						   $('#programFileNameInput').val("* 未找到程序文件,请到平台管理页面进行确认");						  
					   }
				   }
			  });
		  });
		  
		  form.on('select(ProjectProcessInstanceSelectFIlter)',function(data){
			  $('#dataFileNameInput').val('');
			  $('#dataFileNameInput').css('color','black');
			  $.ajax({
				   type:'post',
				   url:'../../plat/findPlatProcessInstanceFileTableByPid',
				   data:{processInstanceId: data.value},
				   success: function(result){
					   var data = result.data;
					   if(data != null){
						   $.each(data,function(i,item){
							   var fileName = item.fileName;
							  if(fileName.substr(fileName.lastIndexOf('.')) == ".mot" || fileName.substr(fileName.lastIndexOf('.')) == ".s19"){								  
								  $('#dataFileNameInput').val(fileName);
								  $('#dataFileNameInput').attr("data-url", item.url);
								  return false;
							  } 
						   });
						   if( $('#dataFileNameInput').val() == ''){
							   $('#dataFileNameInput').css('color','red');
							   $('#dataFileNameInput').val("* 未找到标定数据文件,请到项目管理页面进行确认");
						   }
					   }else{
						   $('#dataFileNameInput').css('color','red');
						   $('#dataFileNameInput').val("* 未找到标定数据文件,请到平台项目页面进行确认");
					   }
				   }
			  });
		  });
			
		  element.render('breadcrumb');
  
});